package xh.lumt.server.processors;

import io.netty.handler.codec.http.FullHttpResponse;
import org.apache.commons.io.IOUtils;
import xh.lumt.util.HttpUtils;

import java.io.IOException;
import java.net.URL;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

/**
 * Created by Administrator on 2016/6/25.
 */
public class StaticResourceProcessor extends AbstractProcessor {

    private String uri;

    public StaticResourceProcessor(String s) {
        this.uri = s;
    }

    public FullHttpResponse process() {
        URL staticFile = Thread.currentThread().getContextClassLoader().getResource("statics" + "/" + uri);
        if (staticFile == null) {
            return HttpUtils._404();
        }

        try {
            byte[] content = IOUtils.toByteArray(staticFile.openStream());
            FullHttpResponse response = defaultResponse(content);

            if (uri.endsWith(".css")) {
                response.headers().set(CONTENT_TYPE, "text/css");
            } else {
                response.headers().set(CONTENT_TYPE, "text/html");
            }
            return response;

        } catch (IOException e) {
            e.printStackTrace();
            return HttpUtils._404();
        }
    }


    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }
}
